package com.house.service;

import com.house.dao.SpitDao;
import com.house.pojo.Spit;
import com.house.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;


    public List<Spit> findAll(){
       return spitDao.findAll();
    }

    public Spit findById(String id){
        return spitDao.findById(id).get();
    }

    public void addspit(Spit spit) {
        spit.set_id(idWorker.nextId()+"");
        spit.setPublishtime(new Date());//发布时
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态
        //如果当前添加的吐槽有父节点，那么他的回复数得加1
        if(spit.getParentid()!=null&&"".equals(spit.getParentid())){
            Query query=new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));
            Update update=new Update();
            update.inc("comment",1);
            mongoTemplate.updateFirst(query,update,"spit");
        }
        spitDao.save(spit);
    }

    public void update(Spit spit) {
        spitDao.save(spit);
    }

    public void del(String spitId) {
        spitDao.deleteById(spitId);
    }

    public Page<Spit> findByParentid(String parentid,int page,int size){
       return spitDao.findByParentid(parentid, PageRequest.of(page-1,size));
    }

    public void thumbup(String spitId) {
        /*方式一
        Spit spit = spitDao.findById(spitId).get();
        spit.setThumbup((spit.getThumbup()==null?0:spit.getThumbup())+1);
        spitDao.save(spit);*/
      //  方式二 原生mongod命令来实现自增 db.spit.update({"_id:1"},inc:{thumbup:NumberInt(11)})
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(spitId));
        Update updata=new Update();
        updata.inc("thumbup",1);
        mongoTemplate.updateFirst(query,updata,"spit");
    }
}
